package com.szly.phm.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.szly.phm.common.entity.dto.FaFault.RadarTypeFaultsNumDTO;
import com.szly.phm.common.entity.dto.screen.*;
import com.szly.phm.common.entity.po.*;
import com.szly.phm.common.entity.result.PageResult;
import com.szly.phm.common.entity.result.RootResponse;
import com.szly.phm.common.entity.vo.screen.*;
import com.szly.phm.common.mapper.*;
import com.szly.phm.common.service.IKeyPerformanceService;
import com.szly.phm.common.utils.BeanCopyUtils;
import com.szly.phm.common.utils.DateUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class KeyPerformanceServiceImpl implements IKeyPerformanceService {
    private final CbandRealdataMapper cbandRealdataMapper;
    private final RaRadarMapper raRadarMapper;
    private final TimedTaskFaultResultMapper timedTaskFaultResultMapper;
    private final RaSystemMapper raSystemMapper;
    private final DisplayLocationInfoMapper displayLocationInfoMapper;
    private final FaEnsurePlanMapper faEnsurePlanMapper;
    private final FaFaultRecordMapper faFaultRecordMapper;
    private final HealthScoreMapper healthScoreMapper;
    private  final  SysParameterMapper sysParameterMapper;
    @Override
    public RootResponse selectKeyPerformances(KeyPerformancesDTO keyPerformancesDTO) {
        Map<String, Object> reMap1 = new HashMap<>();
        List<String> dateList = new ArrayList<>();
        var wrapper = new LambdaQueryWrapper<RaRadar>();
        wrapper.eq(RaRadar::getIsSoftDelete,0);
        wrapper.eq(RaRadar::getId,keyPerformancesDTO.getRadarId());
        var raRadar= raRadarMapper.selectOne(wrapper);
        if(raRadar.getDataTableName()!=null) {
            keyPerformancesDTO.setTable(raRadar.getDataTableName());
            if (keyPerformancesDTO.getPreviousTime() != null && !keyPerformancesDTO.getPreviousTime().isEmpty()) {
                keyPerformancesDTO.setPreviousTime(keyPerformancesDTO.getPreviousTime().replace("-", "").replace(" ", "").replace(":", ""));
            }
            else if(keyPerformancesDTO.getStartTime()!=null&&!keyPerformancesDTO.getStartTime().isEmpty()&&keyPerformancesDTO.getEndTime()!=null&&!keyPerformancesDTO.getEndTime().isEmpty())
            {
                keyPerformancesDTO.setStartTime(keyPerformancesDTO.getStartTime().replace("-", "")+"000000");
                keyPerformancesDTO.setEndTime(keyPerformancesDTO.getEndTime().replace("-", "")+"235959");
            }
            else{
                if (keyPerformancesDTO.getType() == 0) {
                    String strDateFormat = "yyyyMMddHHmmss";
                    SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                    keyPerformancesDTO.setStartTime(sdf.format(DateUtils.getDayFistDateTime(new Date())));
                    keyPerformancesDTO.setEndTime(sdf.format(DateUtils.getDayLastDateTime(new Date())));
                } else if (keyPerformancesDTO.getType() == 1) {
                    String strDateFormat = "yyyyMMddHHmmss";
                    SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                    keyPerformancesDTO.setStartTime(sdf.format(DateUtils.getMonthFistDateTime(new Date())));
                    keyPerformancesDTO.setEndTime(sdf.format(DateUtils.getMonthLastDateTime(new Date())));
                } else {
                    String strDateFormat = "yyyyMMddHHmmss";
                    SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                    keyPerformancesDTO.setStartTime(DateUtils.getFirstDayByQuarter(new Date(), strDateFormat));
                    keyPerformancesDTO.setEndTime(DateUtils.getLastDayByQuarter(new Date(), strDateFormat));
                }
            }

            for(String s:keyPerformancesDTO.getField().split(",")){
                AtomicInteger a= new AtomicInteger(0);
                List<String> valueList = new ArrayList<>();
                Map<String, Object> reMap = new HashMap<>();
                keyPerformancesDTO.setField(s);
                List<Map<String, Object>> cbanRealField = cbandRealdataMapper.selectCbanRealField(keyPerformancesDTO);
                cbanRealField.forEach(p -> {
                    valueList.add(p.get(keyPerformancesDTO.getField()).toString());
                    if(a.get()==0){
                        String rDate = "";
                        String date = p.get("uptime").toString();
                        rDate += date.substring(0, 4);
                        rDate += "-" + date.substring(4, 6);
                        rDate += "-" + date.substring(6, 8);
                        rDate += " " + date.substring(8, 10);
                        rDate += ":" + date.substring(10, 12);
                        rDate += ":" + date.substring(12, 14);
                        dateList.add(rDate);
                    }
                });
                reMap.put("dateList", dateList);
                reMap.put("valueList", valueList);
                var map=cbandRealdataMapper.selectRealUnit(keyPerformancesDTO.getField());
                reMap.put("unit",map==null?null:map.get("unit"));
                reMap1.put(s,reMap);
                a.set(1);
            }
            }
        reMap1.put("dateList",dateList);
        return RootResponse.success(reMap1);
    }

    @Override
    public RootResponse radarScoreHistoricalData(ScoreHistoricalDataDTO keyPerformancesDTO) {
        Map<String, Object> reMap1 = new HashMap<>();
        List<Object> dateList = new ArrayList<>();
        var wrapper = new LambdaQueryWrapper<RaRadar>();
        wrapper.eq(RaRadar::getIsSoftDelete,0);
        wrapper.eq(RaRadar::getId,keyPerformancesDTO.getRadarId());
        var raRadar= raRadarMapper.selectOne(wrapper);
        if(raRadar.getDataTableName()!=null) {
            if (keyPerformancesDTO.getPreviousTime() == null||"".equals(keyPerformancesDTO.getPreviousTime() )) {
                if (keyPerformancesDTO.getType() == 0) {
                    String strDateFormat = "yyyyMMddHHmmss";
                    SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                    keyPerformancesDTO.setStartTime(sdf.format(DateUtils.getDayFistDateTime(new Date())));
                    keyPerformancesDTO.setEndTime(sdf.format(DateUtils.getDayLastDateTime(new Date())));
                } else if (keyPerformancesDTO.getType() == 1) {
                    String strDateFormat = "yyyyMMddHHmmss";
                    SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                    keyPerformancesDTO.setStartTime(sdf.format(DateUtils.getMonthFistDateTime(new Date())));
                    keyPerformancesDTO.setEndTime(sdf.format(DateUtils.getMonthLastDateTime(new Date())));
                } else {
                    String strDateFormat = "yyyyMMddHHmmss";
                    SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                    keyPerformancesDTO.setStartTime(DateUtils.getFirstDayByQuarter(new Date(), strDateFormat));
                    keyPerformancesDTO.setEndTime(DateUtils.getLastDayByQuarter(new Date(), strDateFormat));
                }
            }
                List<Double> valueList = new ArrayList<>();
                Map<String, Object> reMap = new HashMap<>();
                List<Map<String, Object>> cbanRealField = cbandRealdataMapper.selectCbanRealField2(keyPerformancesDTO);
                cbanRealField.forEach(p -> {
                    valueList.add(new BigDecimal(Float.valueOf(p.get("radar_score").toString())).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                        dateList.add(p.get("create_date_time"));

                });
                reMap.put("dateList", dateList);
                reMap.put("valueList", valueList);
                reMap1.put("radar_score",reMap);

        }
        reMap1.put("dateList",dateList);
        return RootResponse.success(reMap1);
    }

    @Override
    public RootResponse realTimeRadarScoreData(RealTimeRadarScoreDataDTO keyPerformancesDTO) {
        var rMap=healthScoreMapper.realTimeRadarScoreData(keyPerformancesDTO.getRadarId());
        var SubsystemVOs= cbandRealdataMapper.selectFixedSubsystem(keyPerformancesDTO.getRadarId());
        for(var s:SubsystemVOs){
            var subsystemStatusVO=new SubsystemStatusVO();
            BeanCopyUtils.copy(s,subsystemStatusVO);
            var timedTaskFaultResult=timedTaskFaultResultMapper.selectTimedTaskFaultResultNowById(s.getId(),keyPerformancesDTO.getRadarId());
            if(timedTaskFaultResult!=null){
                if(timedTaskFaultResult.getSwitchFault()!=0||timedTaskFaultResult.getSwitchFault()!=0){
                    if(rMap.get("status")!=null){
                        if(Integer.valueOf(rMap.get("status").toString())!=2){
                            rMap.put("status",2);
                        }}
                    else {
                        rMap.put("status",2);
                    }
                }
//                        subsystemStatusVO.setStatus(2);
                else if(timedTaskFaultResult.getNonSwitchLow()!=0){
                    if(rMap.get("status")!=null){
                        if(Integer.valueOf(rMap.get("status").toString())!=2){
                            rMap.put("status",1);
                        }}else {
                        rMap.put("status",1);
                    }
//                        subsystemStatusVO.setStatus(1);
                }else {
                    if(rMap.get("status")!=null){
                        if(Integer.valueOf(rMap.get("status").toString())!=2&&Integer.valueOf(rMap.get("status").toString())!=1){
                            rMap.put("status",0);
                        }
                    }else {
                        rMap.put("status",0);
                    }
//                        subsystemStatusVO.setStatus(0);
                }

            }else {
                var wrapper = new LambdaQueryWrapper<RaSystem>();
                wrapper.eq(RaSystem::getIsSoftDelete,false);
                wrapper.eq(RaSystem::getId,s.getId());
                var raSystem= raSystemMapper.selectOne(wrapper);
                var map2=new HashMap<>();
                map2.put("status",2);
                map2.put("picture",raSystem.getPerfectIcon());
                if(rMap!=null){
                    if(rMap.get("status")!=null){
                        if(Integer.valueOf(rMap.get("status").toString())!=2||Integer.valueOf(rMap.get("status").toString())!=1){
                            rMap.put("status",2);
                        }
                    }else {
                        rMap.put("status",2);
                    }
                }else {
                    rMap=new HashMap<>();
                    if(rMap.get("status")!=null){
                        if(Integer.valueOf(rMap.get("status").toString())!=2||Integer.valueOf(rMap.get("status").toString())!=1){
                            rMap.put("status",2);
                        }
                    }else {
                        rMap.put("status",2);
                        rMap.put("radar_score",0);
                    }
                }


            }
        }
        rMap.put("radar_score",new BigDecimal((double)rMap.get("radar_score")).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        return RootResponse.success( rMap);
    }

    @Override
    public RootResponse selectRealTimeFiled(RealTimeFiledDTO realTimeFiledDTO) {
        float faultThreshold=1.1f;
        var map2s=sysParameterMapper.selectHealthParameter();
        for(Map<String,Object> map2:map2s){
            if(map2.get("faultThreshold")!=null){
                faultThreshold=1+ Float.parseFloat(map2.get("faultThreshold").toString());
            }
        }

        Map<String,Map<String,Object>> rMap=new HashMap<>();
        //
        var wrapper = new LambdaQueryWrapper<RaRadar>();
        wrapper.eq(RaRadar::getIsSoftDelete,0);
        wrapper.eq(RaRadar::getId,realTimeFiledDTO.getRadarId());
        var raRadar= raRadarMapper.selectOne(wrapper);
        if(raRadar.getDataTableName()!=null){
            realTimeFiledDTO.setTable(raRadar.getDataTableName());
            Map<String,Object> cbanRealField= cbandRealdataMapper.selectRealField(realTimeFiledDTO);
            String rDate = "";
            String date = cbanRealField.get("uptime").toString();
            rDate += date.substring(0, 4);
            rDate += "-" + date.substring(4, 6);
            rDate += "-" + date.substring(6, 8);
            rDate += " " + date.substring(8, 10);
            rDate += ":" + date.substring(10, 12);
            rDate += ":" + date.substring(12, 14);
            Map<String,Object> map1=  new HashMap<>();
            map1.put("time",rDate);
            rMap.put("time",map1);
            List<String> units= new ArrayList<>();
            List<String> displayName= new ArrayList<>();
            List<String> displayPName= new ArrayList<>();
            List<String> cName= new ArrayList<>();
            List<Float> maxs= new ArrayList<>();
            List<Float> mins= new ArrayList<>();
            for (Map.Entry<String, Object> entry : cbanRealField.entrySet()){
                if(!"uptime".equals(entry.getKey())){
                    var unit1=cbandRealdataMapper.selectRealUnit(entry.getKey());
                    if(unit1!=null){
                        String unit=unit1.get("unit")==null?"":unit1.get("unit").toString();
                        units.add(unit);
                        displayName.add(unit1.get("name")==null?"":unit1.get("name").toString());
                        displayPName.add(unit1.get("pname")==null?"":unit1.get("pname").toString());
                        cName.add(unit1.get("cName")==null?"":unit1.get("cName").toString());
                        maxs.add(unit1.get("max")==null?0:Float.valueOf(unit1.get("max").toString()));
                        mins.add(unit1.get("min")==null?0:Float.valueOf(unit1.get("min").toString()));
                    }else {
                        units.add("");
                        displayName.add("");
                        displayPName.add("");
                        cName.add("");
                        maxs.add(0.0f);
                        mins.add(0.0f);
                    }
                }
            }
            int i=0;
            for (Map.Entry<String, Object> entry : cbanRealField.entrySet()) {
                if(!entry.getKey().equals("uptime")){
                    Map<String,Object> map=  new HashMap<>();
                    map.put("data",entry.getValue());
                    map.put("unit",units.get(i));
                    map.put("displayName",displayName.get(i));
                    map.put("displayPName",displayPName.get(i));
                    map.put("cName",cName.get(i));
                    map.put("max",maxs.get(i));
                    if(entry.getValue()!=null&&maxs.get(i)!=null&&maxs.get(i)>0&&Float.parseFloat(entry.getValue().toString())>maxs.get(i)*faultThreshold){
                        map.put("status",1);
                    }
                    if(entry.getValue()!=null&&maxs.get(i)!=null&&maxs.get(i)<0&&Float.parseFloat(entry.getValue().toString())>maxs.get(i)*(2-faultThreshold)){
                        map.put("status",1);
                    }
                if(entry.getValue()!=null&&mins.get(i)!=null&&mins.get(i)>0&&Float.parseFloat(entry.getValue().toString())<mins.get(i)*(2-faultThreshold)){

                        map.put("status",1);
                    }
                    if(entry.getValue()!=null&&mins.get(i)!=null&&mins.get(i)<0&&Float.parseFloat(entry.getValue().toString())<mins.get(i)*faultThreshold){

                        map.put("status",1);
                    }
                    if(map.get("status")==null){
                        map.put("status",0);
                    }
                    rMap.put(entry.getKey(),map);
                }
                i++;
            }
        }
        return RootResponse.success(rMap);
    }

    @Override
    public RootResponse selectSubsystemData(SubsystemDataDTO realTimeFiledDTO) {
        var map1s=sysParameterMapper.selectHealthParameter();
        float faultThreshold=1.1f;
        for(Map<String,Object> map1:map1s){
            if(map1.get("faultThreshold")!=null){
                faultThreshold=1+ Float.parseFloat(map1.get("faultThreshold").toString());
            }
        }
        String rDate="";
       var timedTaskFaultResult=timedTaskFaultResultMapper.selectTimedTaskFaultResult(realTimeFiledDTO);
        List<SubsystemDataChildVO> showDatas=new ArrayList<>();
        var importData = new ArrayList<Map<String,Object>>();
        var subsystemDataVO= new SubsystemDataVO();
        var wrapper = new LambdaQueryWrapper<RaRadar>();
        wrapper.eq(RaRadar::getIsSoftDelete,0);
        wrapper.eq(RaRadar::getId,realTimeFiledDTO.getRadarId());
       var raRadar= raRadarMapper.selectOne(wrapper);
var fiRealTimeFileStructures=cbandRealdataMapper.selectFiRealTimeFileStructure(realTimeFiledDTO);
if(raRadar.getDataTableName()!=null){
    var map=cbandRealdataMapper.selectRealField1(raRadar.getDataTableName());
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        String regex = ".*[a-zA-Z]+.*";
        Matcher m = Pattern.compile(regex).matcher(entry.getValue().toString());
        if(!"".equals(entry.getValue())&& !m.matches()) {
            var rMap =new HashMap<String,Object>();
            for(FiRealTimeFileStructureVO f:fiRealTimeFileStructures){
                if(f.getEName().equals(entry.getKey())){
                    rMap.put("EName",f.getEName());
                    rMap.put("CName",f.getCName());
                    rMap.put("dataSerial",f.getDataSerial());
                    rMap.put("value",entry.getValue());
                    rMap.put("unit",f.getUnit());
                    rMap.put("picture",f.getIcon());
                    if(entry.getValue()!=null&&f.getMax()!=null&&f.getMax()>0&&Double.parseDouble(entry.getValue().toString())>f.getMax()*faultThreshold){
                        rMap.put("status",1);
                    }
                    if(entry.getValue()!=null&&f.getMax()!=null&&f.getMax()<0&&Double.parseDouble(entry.getValue().toString())>f.getMax()*(2-faultThreshold)){
                        rMap.put("status",1);
                    }
                     if(entry.getValue()!=null&&f.getMin()!=null&&f.getMin()>0&&Double.parseDouble(entry.getValue().toString())<f.getMin()*(2-faultThreshold)){
                        rMap.put("status",1);
                    }
                    if(entry.getValue()!=null&&f.getMin()!=null&&f.getMin()<0&&Double.parseDouble(entry.getValue().toString())<f.getMin()*faultThreshold){
                        rMap.put("status",1);
                    }
                    if(rMap.get("status")==null){
                        rMap.put("status",0);
                    }
                    rMap.put("displayLocationName",f.getDisplayLocationName());
                    rMap.put("order",f.getDisplayorder());
                    if(f.getImportantPara()==1){
                        importData.add(rMap);
                    }
                    if(showDatas==null||showDatas.size()==0) {
                        List<Map<String,Object>> rList=new ArrayList<>();
                        rList.add(rMap);
                        var subsystemDataChildVO=new SubsystemDataChildVO();
                        subsystemDataChildVO.setList(rList);
                        var wrapper1 = new LambdaQueryWrapper<DisplayLocationInfo>();
                        wrapper1.eq(DisplayLocationInfo::getIsSoftDelete,0);
                        wrapper1.eq(DisplayLocationInfo::getId,f.getPid());
                        var displayLocationInfo= displayLocationInfoMapper.selectOne(wrapper1);
                        if(displayLocationInfo!=null){
                            subsystemDataChildVO.setDisplayName( displayLocationInfo.getName());
                            subsystemDataChildVO.setOrder(displayLocationInfo.getDisplaySerialNum());
                            showDatas.add(subsystemDataChildVO);
                        }
                    }else {
                        AtomicInteger a=new AtomicInteger(0);
                        for(var s:showDatas){
                            var wrapper1 = new LambdaQueryWrapper<DisplayLocationInfo>();
                            wrapper1.eq(DisplayLocationInfo::getIsSoftDelete,0);
                            wrapper1.eq(DisplayLocationInfo::getId,f.getPid());
                            var displayLocationInfo= displayLocationInfoMapper.selectOne(wrapper1);
                            if(displayLocationInfo!=null&&s.getDisplayName().equals(displayLocationInfo.getName())){
                                s.getList().add(rMap);
                                a.set(1);
                            }
                        }
                        if(a.get()==0){
                            List<Map<String,Object>> rList=new ArrayList<>();
                            rList.add(rMap);
                            var subsystemDataChildVO=new SubsystemDataChildVO();
                            subsystemDataChildVO.setList(rList);
                            var wrapper1 = new LambdaQueryWrapper<DisplayLocationInfo>();
                            wrapper1.eq(DisplayLocationInfo::getIsSoftDelete,0);
                            wrapper1.eq(DisplayLocationInfo::getId,f.getPid());
                            var displayLocationInfo= displayLocationInfoMapper.selectOne(wrapper1);
                            if(displayLocationInfo!=null){
                                subsystemDataChildVO.setDisplayName(displayLocationInfo.getName());
                                subsystemDataChildVO.setOrder(displayLocationInfo.getDisplaySerialNum());
                                showDatas.add(subsystemDataChildVO);
                            }
                        }
                    }
                }
            }
        }
    }
    String date=map.get("uptime").toString();
    rDate+=date.substring(0,4);
    rDate+="-"+date.substring(4,6);
    rDate+="-"+date.substring(6,8);
    rDate+=" "+date.substring(8,10);
    rDate+=":"+date.substring(10,12);
    rDate+=":"+date.substring(12,14);
}
        subsystemDataVO.setImportData(importData);
        subsystemDataVO.setShowData(showDatas);
        subsystemDataVO.setTime(rDate);
        var wrapper1 = new LambdaQueryWrapper<RaSystem>();
        wrapper1.eq(RaSystem::getIsSoftDelete,0);
        wrapper1.eq(RaSystem::getId,realTimeFiledDTO.getSubsystemId());
        var raSystem=raSystemMapper.selectOne(wrapper1);
        if(timedTaskFaultResult!=null&&raSystem!=null){
            if(timedTaskFaultResult.getSwitchFault()!=0||timedTaskFaultResult.getNonSwitchFault()!=0){
                subsystemDataVO.setPictureStatus(raSystem.getFaultIcon());
                subsystemDataVO.setStatus("故障");
            }else if(timedTaskFaultResult.getNonSwitchLow()!=0){
                subsystemDataVO.setPictureStatus(raSystem.getLowIcon());
                subsystemDataVO.setStatus("弱化");
            }else {
                subsystemDataVO.setPictureStatus(raSystem.getPerfectIcon());
                subsystemDataVO.setStatus("正常");
            }
        }else {
            if(raSystem!=null){
                subsystemDataVO.setPictureStatus(raSystem.getPerfectIcon());
            }
            subsystemDataVO.setStatus("正常");
        }
        return RootResponse.success(subsystemDataVO);
    }

    @Override
    public RootResponse selectSubsystem(String radarId) {
        List<SubsystemVO>  subsystemVOS=cbandRealdataMapper.selectSubsystem(radarId);
        return RootResponse.success(subsystemVOS);
    }



    @Override
    public RootResponse selectAdaptationParameters(SystemAdaptationParameters realTimeFiledDTO) {
        var wrapper = new LambdaQueryWrapper<RaRadar>();
        wrapper.eq(RaRadar::getIsSoftDelete,0);
        wrapper.eq(RaRadar::getId,realTimeFiledDTO.getRadarId());
        var raRadar= raRadarMapper.selectOne(wrapper);
        realTimeFiledDTO.setTable(raRadar.getDataTableName());
      if(realTimeFiledDTO.getStartTime()!=null&&!realTimeFiledDTO.getStartTime().isEmpty()&&realTimeFiledDTO.getEndTime()!=null&&!realTimeFiledDTO.getEndTime().isEmpty())
        {
            realTimeFiledDTO.setStartTime(realTimeFiledDTO.getStartTime().replace("-", "")+"000000");
            realTimeFiledDTO.setEndTime(realTimeFiledDTO.getEndTime().replace("-", "")+"235959");
        }
       var realFieldChange= cbandRealdataMapper.selectRealFieldChange(realTimeFiledDTO.getRadarId(),realTimeFiledDTO.getField(),realTimeFiledDTO.getTable(),(realTimeFiledDTO.getPageNum()-1)*10,realTimeFiledDTO.getPageSize(),realTimeFiledDTO.getStartTime(),realTimeFiledDTO.getEndTime());
        realFieldChange.forEach(r->{
            String rDate = "";
            if(r.get("uptime")!=null){
                String date =  r.get("uptime").toString();
                rDate += date.substring(0, 4);
                rDate += "-" + date.substring(4, 6);
                rDate += "-" + date.substring(6, 8);
                rDate += " " + date.substring(8, 10);
                rDate += ":" + date.substring(10, 12);
                rDate += ":" + date.substring(12, 14);
            }
            r.put("uptime",rDate);
        });
       return RootResponse.success(PageResult.page(realFieldChange, realTimeFiledDTO.getPageNum(), realTimeFiledDTO.getPageSize(), cbandRealdataMapper.selectRealFieldChangeCount(realTimeFiledDTO.getTable(),realTimeFiledDTO.getRadarId(),realTimeFiledDTO.getStartTime(),realTimeFiledDTO.getEndTime())));
//
    }

    @Override
    public RootResponse selectSubsystemMonthlyStatus(SubsystemMonthlyStatus realTimeFiledDTO) throws ParseException {
      var rMap=new HashMap<>();
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        var date=sdf.parse(realTimeFiledDTO.getTime()+"-1 00:00:00");
        realTimeFiledDTO.setStartTime(sdf.format(DateUtils.getMonthFistDateTime(date)));
        realTimeFiledDTO.setEndTime(sdf.format(DateUtils.getMonthLastDateTime(date)));
    cbandRealdataMapper.selectSubsystemMonthlyStatus(realTimeFiledDTO).forEach(c->{
        if(Integer.valueOf(c.get("nonSwitchLow").toString())!=0){
            rMap.put(c.get("time"),1);

        }else if(Integer.valueOf(c.get("nonSwitchFault").toString())!=0||Integer.valueOf(c.get("switchFault").toString())!=0){
            rMap.put(c.get("time"),2);
        }
        else {
            rMap.put(c.get("time"),0);
        }
        });
        return RootResponse.success(rMap);
    }

    @Override
    public RootResponse selectSubsystemStatus(String radarId) {
        var map=new HashMap<>();
        var map1=new HashMap<>();
        var newList=new ArrayList<SubsystemStatusVO>();
       var SubsystemVOs= cbandRealdataMapper.selectSubsystem(radarId);
       for(var s:SubsystemVOs){

           var subsystemStatusVO=new SubsystemStatusVO();
           BeanCopyUtils.copy(s,subsystemStatusVO);
           var timedTaskFaultResult=timedTaskFaultResultMapper.selectTimedTaskFaultResultNowById(s.getId(),radarId);

           if(timedTaskFaultResult!=null){
               var map2=new HashMap<>();
               if(map1.get("status")!=null){
               if(timedTaskFaultResult.getSwitchFault()!=0||timedTaskFaultResult.getSwitchFault()!=0){
                   map2.put("status",2);
                    map2.put("picture",timedTaskFaultResult.getFaultIcon());
                   if(map1.get("status")!=null){
                       if(Integer.valueOf(map1.get("status").toString())!=2){
                           map1.put("status",2);
                       }}
                   else {
                       map1.put("status",2);
                   }
               }
//                        subsystemStatusVO.setStatus(2);
               }else if(timedTaskFaultResult.getNonSwitchLow()!=0){
                   map2.put("status",1);
                   map2.put("picture",timedTaskFaultResult.getLowIcon());
                   if(map1.get("status")!=null){
                   if(Integer.valueOf(map1.get("status").toString())!=2){
                       map1.put("status",1);
                   }}else {
                       map1.put("status",1);
                   }
//                        subsystemStatusVO.setStatus(1);
               }else {
                   map2.put("status",0);
                   map2.put("picture",timedTaskFaultResult.getPerfectIcon());
                   if(map1.get("status")!=null){
                       if(Integer.valueOf(map1.get("status").toString())!=2||Integer.valueOf(map1.get("status").toString())!=1){
                           map1.put("status",0);
                       }
                   }else {
                       map1.put("status",0);
                   }
//                        subsystemStatusVO.setStatus(0);
               }

               newList.add(subsystemStatusVO);
               map.put(timedTaskFaultResult.getSystemName(),map2);
           }
       }
        var rMap=healthScoreMapper.realTimeRadarScoreData(radarId);
        map1.put("score",rMap.get("radar_score"));
        map.put("radar",map1);

        return RootResponse.success(map);
    }

    @Override
    public RootResponse selectEnvironmentalParameters(String radarId) {
        var map2s=sysParameterMapper.selectHealthParameter();
        float faultThreshold=1.1f;
        for(Map<String,Object> map2:map2s){
            if(map2.get("faultThreshold")!=null){
                faultThreshold=1+ Float.parseFloat(map2.get("faultThreshold").toString());
            }
        }
        var RMap=new HashMap<String,Map<String,Object>>();
        var wrapper = new LambdaQueryWrapper<RaRadar>();
        wrapper.eq(RaRadar::getIsSoftDelete,false);
        wrapper.eq(RaRadar::getId,radarId);
       var raRadar= raRadarMapper.selectOne(wrapper);
       if(raRadar.getDataTableName()!=null){
           var environmentalParametersVOs=cbandRealdataMapper.selectEnvironmentalParameters(raRadar.getDataTableName(),radarId);
           for (Map.Entry<String, Object> entry : environmentalParametersVOs.entrySet()){
               Map<String,Object> map=new HashMap<>();
              var map1= cbandRealdataMapper.selectRealUnit(entry.getKey());
              map.put("value",entry.getValue());
               if(map1!=null){
                   map.put("unit",map1.get("unit"));
                   if(entry.getValue()!=null&&map1.get("max")!=null&&Float.parseFloat(map1.get("max").toString())>0&&Float.parseFloat(entry.getValue().toString())>Float.parseFloat(map1.get("max").toString())*faultThreshold){
                       map.put("status",1);
                   }
                   if(entry.getValue()!=null&&map1.get("max")!=null&&Float.parseFloat(map1.get("max").toString())<0&&Float.parseFloat(entry.getValue().toString())>Float.parseFloat(map1.get("max").toString())*(2-faultThreshold)){
                       map.put("status",1);
                   }
                    if(entry.getValue()!=null&&map1.get("min")!=null&&Float.parseFloat(map1.get("min").toString())>0&&Float.parseFloat(entry.getValue().toString())<Float.parseFloat(map1.get("min").toString())*(2-faultThreshold)){

                       map.put("status",1);
                   }
                   if(entry.getValue()!=null&&map1.get("min")!=null&&Float.parseFloat(map1.get("min").toString())<0&&Float.parseFloat(entry.getValue().toString())<Float.parseFloat(map1.get("min").toString())*faultThreshold){

                       map.put("status",1);
                   }
                   if(map.get("status")==null){
                       map.put("status",0);
                   }
               }else {
                   map.put("status",0);
                   map.put("unit",null);
               }
               RMap.put(entry.getKey(),map);
           }
          return RootResponse.success(RMap);
       }
        return RootResponse.success();
    }

    @Override
    public RootResponse selectBusinessProcess(String radarId,String time,String areaId) {
        String[] date=new String[2];
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        if(time!=null){
           String[] s= time.split("-");
            if(s.length!=0){
                date[0]=s[0]+"-01-01 00:00:00";
                date[1]=s[0]+"-12-31 24:59:59";
            }
        }else {
            date[0]=sdf.format(DateUtils.getYearFistDateTime(new Date()));
            date[1]=sdf.format(DateUtils.getYearLastDateTime(new Date()));
        }
        String strDateFormat1 = "yyyy-MM";
        SimpleDateFormat sdf1 = new SimpleDateFormat(strDateFormat1);
        var newList=new ArrayList<BusinessProcessVO>();
        var faEnsurePlan=faEnsurePlanMapper.selectEnsurePlanSystemMonth(radarId,areaId);
        faEnsurePlan.forEach(m->{
            try {
                BusinessProcessVO businessProcessVOOld=null;
                int j=0;
                for(BusinessProcessVO businessProcessVO:newList){
                    if(businessProcessVO.getId().equals(m.get("system_id").toString())){
                        j=1;
                    }
                    businessProcessVOOld= businessProcessVO;
                }
                if(j==0){
                    var startDate= sdf.parse(date[0]);
                    var map=new LinkedHashMap<String,Object>();
                    for(int i=0;i<12;i++){
                        map.put(sdf1.format(startDate),0);
                        startDate=DateUtils.addMonth(startDate,1);
                    }
                    var businessProcessVO= new BusinessProcessVO();
                    businessProcessVO.setId(m.get("system_id").toString());
                    businessProcessVO.setName(m.get("system_name").toString());
                    faEnsurePlanMapper.selectEnsurePlanRecordSystemMonth(m.get("ensure_plan_id").toString(), date[0],  date[1]).forEach(f->{
                        if(Integer.valueOf(f.get("total").toString())!=0){
                            map.put(f.get("time").toString(),1);
                        }else {
                            map.put(f.get("time").toString(),0);
                        }
                    });
                    businessProcessVO.setData(map);
                    newList.add(businessProcessVO);
                }else {
                    for(Map<String,Object> map: faEnsurePlanMapper.selectEnsurePlanRecordSystemMonth(m.get("ensure_plan_id").toString(), date[0],  date[1])){
                        if(Integer.valueOf(map.get("total").toString())!=0){
                            businessProcessVOOld.getData().put(map.get("time").toString(),1);
                        }else {
                            businessProcessVOOld.getData().put(map.get("time").toString(),0);
                        }
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        });
        return RootResponse.success(newList);
    }

    @Override
    public RootResponse selectFixedSubsystemFixedStatus(String radarId) {
        var map=new HashMap<>();
        var map1=new HashMap<>();
//        List<Float> wight=new ArrayList<>();
//        List<Double> systemScore=new ArrayList<>();
//        var systemWightTotal=0;
        var newList=new ArrayList<SubsystemStatusVO>();
        var SubsystemVOs= cbandRealdataMapper.selectFixedSubsystem(radarId);
        for(var s:SubsystemVOs){
            var subsystemStatusVO=new SubsystemStatusVO();
            BeanCopyUtils.copy(s,subsystemStatusVO);
            var timedTaskFaultResult=timedTaskFaultResultMapper.selectTimedTaskFaultResultNowById(s.getId(),radarId);
            if(timedTaskFaultResult!=null){
                var map2=new HashMap<>();
                    if(timedTaskFaultResult.getSwitchFault()!=0||timedTaskFaultResult.getNonSwitchFault()!=0){
                        map2.put("status",2);
                        map2.put("picture",timedTaskFaultResult.getFaultIcon());
                            map1.put("status", 2);
                    }
//                        subsystemStatusVO.setStatus(2);
                else if(timedTaskFaultResult.getNonSwitchLow()!=0){
                    map2.put("status",1);
                    map2.put("picture",timedTaskFaultResult.getLowIcon());
                    if(map1.get("status")!=null){
                        if(Integer.valueOf(map1.get("status").toString())!=2){
                            map1.put("status",1);
                        }}else {
                        map1.put("status",1);
                    }
//                        subsystemStatusVO.setStatus(1);
                }else {
                    map2.put("status",0);
                    map2.put("picture",timedTaskFaultResult.getPerfectIcon());
                    if(map1.get("status")!=null){
                        if(Integer.valueOf(map1.get("status").toString())!=2&&Integer.valueOf(map1.get("status").toString())!=1){
                            map1.put("status",0);
                        }
                    }else {
                        map1.put("status",0);
                    }
//                        subsystemStatusVO.setStatus(0);
                }
//                double  fenmu=timedTaskFaultResult.getSwitch1()*2+timedTaskFaultResult.getNoSwitch();
//                double fenzi= timedTaskFaultResult.getNonSwitchLow();
//                systemScore.add((1-fenzi/fenmu)*100);
//                systemWightTotal+=timedTaskFaultResult.getWeight();
//                wight.add(timedTaskFaultResult.getWeight());
                newList.add(subsystemStatusVO);
                map.put(timedTaskFaultResult.getSystemName(),map2);
            }else {
                var wrapper = new LambdaQueryWrapper<RaSystem>();
                wrapper.eq(RaSystem::getIsSoftDelete,false);
                wrapper.eq(RaSystem::getId,s.getId());
               var raSystem= raSystemMapper.selectOne(wrapper);
                var map2=new HashMap<>();
                    map2.put("status",3);
                    map2.put("picture",raSystem.getPerfectIcon());
                newList.add(subsystemStatusVO);
                map.put(s.getName(),map2);
            }
        }

//        double score=0;
//        int i=0;
//        for(float f:wight){
//            score+=  systemScore.get(i)*f/systemWightTotal;
//            i++;
//        }
    var healthScore=cbandRealdataMapper.selectNowHealthScore(radarId);
        map1.put("score",new BigDecimal(Float.valueOf(healthScore.get("radar_score").toString())).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        map.put("radar",map1);

        return RootResponse.success(map);
    }

    @Override
    public RootResponse selectFixedRealTimeFiled(RealTimeFiledDTO realTimeFiledDTO) {
        realTimeFiledDTO.setField("ElMeasured,AzMeasured,TE,TE_V,MEASURED_VELOCITY1,MEASURED_VELOCITY2,MEASURED_VELOCITY3,MEASURED_VELOCITY4");
        Map<String,Map<String,Object>> rMap=new HashMap<>();
        var wrapper = new LambdaQueryWrapper<RaRadar>();
        wrapper.eq(RaRadar::getIsSoftDelete,0);
        wrapper.eq(RaRadar::getId,realTimeFiledDTO.getRadarId());
        var raRadar= raRadarMapper.selectOne(wrapper);
        if(raRadar.getDataTableName()!=null){
            realTimeFiledDTO.setTable(raRadar.getDataTableName());
            Map<String,Object> cbanRealField= cbandRealdataMapper.selectRealField(realTimeFiledDTO);
            List<String> units= new ArrayList<>();
            List<String> displayName= new ArrayList<>();
            List<String> displayPName= new ArrayList<>();
            List<String> cName= new ArrayList<>();
            List<Float> maxs= new ArrayList<>();
            List<Float> mins= new ArrayList<>();
            String rDate="";
            String date = cbanRealField.get("uptime").toString();
            rDate += date.substring(0, 4);
            rDate += "-" + date.substring(4, 6);
            rDate += "-" + date.substring(6, 8);
            rDate += " " + date.substring(8, 10);
            rDate += ":" + date.substring(10, 12);
            rDate += ":" + date.substring(12, 14);
            Map<String,Object> map1=  new HashMap<>();
            map1.put("time",rDate);
            rMap.put("time",map1);
            for (Map.Entry<String, Object> entry : cbanRealField.entrySet()){
                var unit1=cbandRealdataMapper.selectRealUnit(entry.getKey());
                if(unit1!=null){
                    String unit=unit1.get("unit")==null?"":unit1.get("unit").toString();
                    units.add(unit);
                    displayName.add(unit1.get("name")==null?"":unit1.get("name").toString());
                    displayPName.add(unit1.get("pname")==null?"":unit1.get("pname").toString());
                    cName.add(unit1.get("cName")==null?"":unit1.get("cName").toString());
                    maxs.add(unit1.get("max")==null?0:Float.valueOf(unit1.get("max").toString()));
                    mins.add(unit1.get("min")==null?0:Float.valueOf(unit1.get("min").toString()));
                }else {
                    units.add("");
                    displayName.add("");
                    displayPName.add("");
                    cName.add("");
                    maxs.add(0.0f);
                    mins.add(0.0f);
                }
            }
            int i=0;
            for (Map.Entry<String, Object> entry : cbanRealField.entrySet()) {
                if(!entry.getKey().equals("uptime")){
                    Map<String,Object> map=  new HashMap<>();
                    map.put("data",entry.getValue());
                    map.put("unit",units.get(i));
                    map.put("displayName",displayName.get(i));
                    map.put("displayPName",displayPName.get(i));
                    map.put("cName",cName.get(i));
                    map.put("max",maxs.get(i));
                    map.put("min",mins.get(i));
                    rMap.put(entry.getKey(),map);
                }
                i++;
            }
        }
        return RootResponse.success(rMap);
    }

    @Override
    public RootResponse radarTypeFaultsNum(RadarTypeFaultsNumDTO radarTypeFaultsNumDTO) {
        if(StringUtils.isNotBlank(radarTypeFaultsNumDTO.getStartTime())&&StringUtils.isNotBlank(radarTypeFaultsNumDTO.getEndTime())){
            radarTypeFaultsNumDTO.setStartTime(radarTypeFaultsNumDTO.getStartTime()+" 00:00:00");
            radarTypeFaultsNumDTO.setEndTime(radarTypeFaultsNumDTO.getEndTime()+" 23:59:59");
        }
        Map<String,Integer> rMap=new HashMap<>();
        var mapList= faFaultRecordMapper.selectRadarTypeFaultsNum(radarTypeFaultsNumDTO);
        mapList.forEach(m1->{
            var f=faFaultRecordMapper.selectRaDarTypeName(m1.get("radar_id").toString());
            rMap.put(f.get("name").toString(),Integer.valueOf(m1.get("num").toString()));
        });
       return RootResponse.success(rMap);
    }

    @Override
    public RootResponse systemFaultsNum(RadarTypeFaultsNumDTO radarTypeFaultsNumDTO) {
        if(StringUtils.isNotBlank(radarTypeFaultsNumDTO.getStartTime())&&StringUtils.isNotBlank(radarTypeFaultsNumDTO.getEndTime())){
            radarTypeFaultsNumDTO.setStartTime(radarTypeFaultsNumDTO.getStartTime()+" 00:00:00");
            radarTypeFaultsNumDTO.setEndTime(radarTypeFaultsNumDTO.getEndTime()+" 23:59:59");
        }
        var mapList= faFaultRecordMapper.selectSystemFaultsNum(radarTypeFaultsNumDTO);
        Map<String,Integer> rMap=new HashMap<>();
        faFaultRecordMapper.selectSystem().forEach(m->{
            rMap.put(m.get("name").toString(),0);
            mapList.forEach(m1->{
                if(m1.get("systemId").equals(m.get("id"))){
                    rMap.put(m.get("name").toString(),Integer.valueOf(m1.get("num").toString()));
                }
            });
        });
        return RootResponse.success(rMap);
    }


}
